package org.product.controller;

import com.google.gson.Gson;
import org.product.dao.ProductDao;
import org.product.dao.impl.ProductDaoImpl;
import org.product.entity.Product;
import org.product.factory.DaoFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/api/addProduct.do")
public class AddProductServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 第一：获取页面发送过来的商品信息（合法性验证[略]）
        String id = req.getParameter("productId") ;
        String productName = req.getParameter("productName") ;
        double productPrice = Double.parseDouble(req.getParameter("productPrice")) ;
        int productCount = Integer.parseInt(req.getParameter("productCount")) ;
        String productDesc = req.getParameter("productDesc") ;

        HttpSession session = req.getSession() ;
        System.out.println(session.getId());

        // 第二：创建实体对象，并封装数据
        Product pro = new Product(id,productName,productPrice,productCount,productDesc) ;

        // 第三：创建DAO对象，实现数据添加操作
        ProductDao productDao = DaoFactory.getProductDaoInstance();
        int r = productDao.insert(pro) ;

        // 第四：响应结果
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter() ;

        if(r==1) {
            out.print(new Gson().toJson(successJson("添加成功")));
        } else {
            out.print(new Gson().toJson(successJson("添加失败")));
        }

        // 第五：关闭对象
        out.flush();
        out.close();
    }
}
